package org.answer.controller;

import org.answer.constant.MessageConstant;
import org.answer.entity.Result;
import org.answer.service.BehaviorLogService;
import org.answer.utils.BehaviorLogUtils;
import org.answer.utils.GetUserNameUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.answer.utils.DateUtils;
import org.answer.utils.ErrorMailUtils;
import org.apache.log4j.Logger;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private BehaviorLogService behaviorLogService;

    //log4j日志对象
    private Logger logger = ErrorMailUtils.getLogger();
    @RequestMapping("/getUsername")
    public Result getUsername(HttpServletRequest request){
        try {
            //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            System.out.println("user:"+user);
            String username = user.getUsername();
            // 记录日志
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.USER_LOGIN_SUCCESS));
            return new Result(true,MessageConstant.GET_USERNAME_SUCCESS,username);
        }catch (Exception e){
            behaviorLogService.add(
                    BehaviorLogUtils.getBehaviorLog(
                            GetUserNameUtils.getUsername(),
                            request.getRequestURL().toString(),
                            MessageConstant.USER_LOGIN_FAIL));

            logger.error("异常发生时间：" + DateUtils.getCurrentTime(), e);
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }




}
